package com.android.manghe.quickpay.activity

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.os.CountDownTimer
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import androidx.core.content.ContextCompat
import com.android.base.frame.newactivity.MyActivity
import com.android.base.tools.DateTimeUtil
import com.android.base.tools.ToastUtil
import com.android.manghe.R
import com.android.manghe.common.model.BuyGoodShangMengZhiFuRes
import com.android.manghe.common.model.BuyMemberShangMengZhiFuRes
import com.android.manghe.quickpay.model.ShangMengCardNoInfo
import com.android.manghe.quickpay.presenter.PDCPay
import com.githang.statusbar.StatusBarCompat
import kotlinx.android.synthetic.main.activity_dc_pay.*

/**
 * 储蓄卡支付页面
 */
class DCPayActivity : MyActivity<PDCPay>() {
    private val TotalCount = 60L * 1000
    override fun getLayoutId(): Int {
        return R.layout.activity_dc_pay
    }

    override fun isStatusBarEnabled(): Boolean {
        return false
    }

    override fun initData(savedInstanceState: Bundle?) {
        StatusBarCompat.setStatusBarColor(this, ContextCompat.getColor(this, R.color.white))

        p.cardNoData = intent.getSerializableExtra("cardNoData") as ShangMengCardNoInfo
        p.cardNo = intent.getStringExtra("cardNo")
        p.isSecondPay = intent.getBooleanExtra("secondPay", false)
        val tempOrderDetail = intent.getSerializableExtra("orderDetail")
        if (tempOrderDetail is BuyMemberShangMengZhiFuRes.DataBean.OrderBean) {
            p.buyMemberOrderDetail =
                intent.getSerializableExtra("orderDetail") as BuyMemberShangMengZhiFuRes.DataBean.OrderBean
        } else if (tempOrderDetail is BuyGoodShangMengZhiFuRes.DataBean.OrderBean) {
            p.isBuyGood = true
            p.buyGoodOrderDetail =
                intent.getSerializableExtra("orderDetail") as BuyGoodShangMengZhiFuRes.DataBean.OrderBean
        }


        tvOrderPrice.setOnClickListener {
            layoutDetail.visibility = View.VISIBLE
            ivArrowDown.visibility = View.GONE
            tvOrderPrice.isEnabled = false
        }
        tvTraceTime.setOnClickListener {
            ivArrowDown.visibility = View.VISIBLE
            layoutDetail.visibility = View.GONE
            tvOrderPrice.isEnabled = true
        }
        tvSendCode.setOnClickListener {
            //发送验证码
            val tel = etTel.text.toString().trim()
            val certificateNo = etCertificateNo.text.toString().trim()
            val realName = etRealName.text.toString().trim()
            if (certificateNo.isEmpty()) {
                ToastUtil.showLong(this, "请输入证件号")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(realName)) {
                ToastUtil.showLong(this, "请输入真实姓名")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(tel)) {
                ToastUtil.showLong(this, "请输入银行卡预留手机号")
                return@setOnClickListener
            }
            if (!p.isBuyGood) {
                //购买会员
                p.newOrder(
                    tel,
                    realName,
                    certificateNo
                )
            } else {
                p.sendCode(tel, realName, certificateNo)
            }
        }

        btnPay.setOnClickListener {
            //确认付款
            val certificateNo = etCertificateNo.text.toString().trim()
            val smsCode = etCode.text.toString().trim()
            val tel = etTel.text.toString().trim()
            val realName = etRealName.text.toString().trim()
            if (certificateNo.isEmpty()) {
                ToastUtil.showLong(this, "请输入证件号")
                return@setOnClickListener
            }
            if (TextUtils.isEmpty(realName)) {
                ToastUtil.showLong(this, "请输入真实姓名")
                return@setOnClickListener
            }
            if (tel.isEmpty()) {
                ToastUtil.showLong(this, "请输入银行预留手机号")
                return@setOnClickListener
            }
            if (smsCode.isEmpty()) {
                ToastUtil.showLong(this, "请输入短信验证码")
                return@setOnClickListener
            }
            if (!p.isBuyGood && p.logId == -1) {
                //购买会员，但没发送验证码
                ToastUtil.showLong(this, "请先发送验证码")
                return@setOnClickListener
            }
            p.toPay(smsCode)
        }
        etRealName.addTextChangedListener(getTextWatcher())
        etCertificateNo.addTextChangedListener(getTextWatcher())
        etTel.addTextChangedListener(getTextWatcher())
        etCode.addTextChangedListener(getTextWatcher())

        tvBank.text = p.cardNoData.bank_name
        tvCardNo.text = if (p.cardNo.length == 4) "****${p.cardNo}" else "${
            p.cardNo.substring(
                0,
                3
            )
        }****${p.cardNo.substring(p.cardNo.length - 4, p.cardNo.length)}"
        tvOrderPrice.text =
            "￥${if (p.isBuyGood) p.buyGoodOrderDetail.order_amount else p.buyMemberOrderDetail.amount}"
        tvOrderDesc.text =
            if (p.isBuyGood) p.buyGoodOrderDetail.items[0].subject else p.buyMemberOrderDetail.title
        tvTraceTime.text = DateTimeUtil.longToString(
            if (p.isBuyGood) p.buyGoodOrderDetail.c_time.toLong() else p.buyMemberOrderDetail.c_time.toLong(),
            "yyyy-MM-dd HH:mm:ss"
        )
    }

    private fun getTextWatcher(): TextWatcher {
        return object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {

            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                checkConfirmBtnEnable()
            }

        }
    }

    fun sendCodeOk() {
        startCountDown()
    }

    fun sendCodeFail(text: String?) {
        ToastUtil.showShort(this, if (TextUtils.isEmpty(text)) "发送验证码失败" else text)
    }

    private var mTimer: CountDownTimer? = null
    private fun startCountDown() {
        mTimer = object : CountDownTimer(TotalCount, 1000) {

            override fun onTick(millisUntilFinished: Long) {
                tvSendCode.text = "${(millisUntilFinished / 1000)}s"
                tvSendCode.isClickable = false
            }

            override fun onFinish() {
                tvSendCode.text = "发送验证码"
                tvSendCode.isClickable = true
            }
        }
        mTimer!!.start()
    }

    private fun stopCountDown() {
        mTimer?.let {
            it.cancel()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        stopCountDown()
    }

    fun paySuccess() {
        setResult(Activity.RESULT_OK)
        finish()
    }

    fun payFail() {
        val intent = Intent()
        intent.putExtra("fail", true)
        setResult(Activity.RESULT_OK, intent)
        finish()
    }

    private fun checkConfirmBtnEnable() {
        val enable = etRealName.text.toString().trim().isNotEmpty()
                && etCertificateNo.text.toString().trim().isNotEmpty()
                && etTel.text.toString().trim().isNotEmpty()
                && etCode.text.toString().trim().isNotEmpty()
        btnPay.isEnabled = enable
        btnPay.setTextColor(
            ContextCompat.getColor(
                this,
                if (!enable) R.color.white else R.color.colorFont33
            )
        )
        btnPay.setBackgroundResource(if (!enable) R.drawable.btn_disable_round_selector else R.drawable.btn_primary_round_selector)
    }
}